# encoding: UTF-8
# user：admin at 2018/3/7

import itchat
from collections import Counter
import matplotlib.pyplot as plt
import re
from snownlp import SnowNLP
import jieba.analyse
import jieba
import numpy as np
from PIL import Image
from wordcloud import WordCloud

def analyseSex(friends):
    #print(friends[1:])
    sexs=list(map(lambda x:x['Sex'],friends[1:]))
    #print(Counter(sexs).items())
    counts=list(map(lambda x:x[1],Counter(sexs).items()))
    labels=['女','男','未知']
    colors = ['yellowgreen', 'lightskyblue', 'red']
    plt.figure(figsize=(8,5),dpi=80)
    plt.axes(aspect=1)
    plt.pie(
        counts,
        labels=labels,
        colors=colors,
        labeldistance=1.1,
        autopct='%3.1f%%',
        shadow=False,
        startangle=90,
        pctdistance=0.6
    )
    plt.legend(loc='upper right',)
    title=u'%s的微信好友性别组成' % friends[0]['NickName']
    print(title)
    plt.title(title)
    plt.show()

def analyseSignature(friends):
    signatures=''
    emotions=[]
    pattern=re.compile('1f\d.+')
    #print(friends)
    for friend in friends:
        signature=friend['Signature']
        if signature !=None:
            signature=signature.strip().replace('span','').replace('class','').replace('emoji','')
            signature=re.sub(r'1f(\d.+)','',signature)
            if len(signature)>0:
                nlp=SnowNLP(signature)
                emotions.append(nlp.sentiments)
                signatures+=' '.join(jieba.analyse.extract_tags(signature,5))

    with open('signatures.txt','wt',encoding='utf-8') as file:
        file.write(signatures)

    print(signatures)

    back_coloring=np.array(Image.open('flower.jpg'))
    wordcloud=WordCloud(
        font_path=r'./font/simhei.ttf',
        background_color='white',
        max_words=1200,
        mask=back_coloring,
        max_font_size=75,
        random_state=40,
        width=960,
        height=750,
        margin=15
    )

    wordcloud.generate(signatures)
    plt.imshow(wordcloud)
    plt.axis('off')
    plt.show()
    wordcloud.to_file('signatures.jpg')

    # Signature Emotional Judgment
    count_good = len(list(filter(lambda x: x > 0.66, emotions)))
    count_normal = len(list(filter(lambda x: x >= 0.33 and x <= 0.66, emotions)))
    count_bad = len(list(filter(lambda x: x < 0.33, emotions)))
    labels = [u'负面消极', u'中性', u'正面积极']
    values = (count_bad, count_normal, count_good)
    plt.rcParams['font.sans-serif'] = ['simHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.xlabel(u'情感判断')
    plt.ylabel(u'频数')
    plt.xticks(range(3), labels)
    plt.legend(loc='upper right', )
    plt.bar(range(3), values, color='rgb')
    plt.title(u'%s的微信好友签名信息情感分析' % friends[0]['NickName'])
    plt.show()

if __name__=='__main__':
    itchat.auto_login(hotReload = True)
    friends = itchat.get_friends(update = True)
    #analyseSex(friends)
    analyseSignature(friends)